package com.sjd.farm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sjd.common.core.domain.AjaxResult;
import com.sjd.common.core.domain.model.LoginUser;
import com.sjd.farm.domain.SjdFarmGoodsDO;
import com.sjd.farm.domain.dto.goods.*;
import com.sjd.farm.mapper.SjdFarmGoodsMapper;
import com.sjd.farm.service.ISjdFarmLandClaimOrderService;
import com.sjd.farm.service.SjdFarmGoodsService;
import com.sjd.wx.utils.ThirdSessionHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : Mr.s
 * @version : 1.0
 * @description : 四季豆农场商品service
 * @date : 2022-01-28 14:53
 */
@Slf4j
@Service
public class SjdFarmGoodsServiceImpl implements SjdFarmGoodsService {

    @Autowired
    private SjdFarmGoodsMapper farmGoodsMapper;

    @Autowired
    ISjdFarmLandClaimOrderService farmLandClaimOrderService;

    /**
     * 增加农场商品 管理平台
     *
     * @param requestDTO requestDTO
     * @param loginUser  loginUser
     * @return return
     */
    @Override
    public AjaxResult add(SjdWebSiteFarmGoodsAddRequestDTO requestDTO, LoginUser loginUser) {
        log.info("管理员{} 添加商品:{}", loginUser.getUserId(), requestDTO);
        SjdFarmGoodsDO farmGoodsDO = SjdFarmGoodsDO.builder()
                .goodsName(requestDTO.getGoodsName())
                .bigPicture(requestDTO.getBigPicture())
                .goodsTips(requestDTO.getGoodsTips())
                .goodsPrice(requestDTO.getGoodsPrice())
                .goodsDetail(requestDTO.getGoodsDetail())
                .goodsLevel(requestDTO.getGoodsLevel())
                .goodsTypeClass(requestDTO.getGoodsTypeClass())
                .goodsStorage(requestDTO.getGoodsStorage())
                .creatorId(loginUser.getUserId())
                .build();
        List<String> goodsPicture = requestDTO.getGoodsPicture();
        String pictureJson = JSON.toJSONString(goodsPicture);
        farmGoodsDO.setGoodsPicture(pictureJson);
        farmGoodsMapper.insertSelective(farmGoodsDO);
        return AjaxResult.success();
    }

    /**
     * 修改农场商品 管理平台
     *
     * @param requestDTO requestDTO
     * @param loginUser  loginUser
     * @return return
     */
    @Override
    public AjaxResult updateFarmGoods(SjdWebSiteFarmGoodsUpdateRequestDTO requestDTO, LoginUser loginUser) {
        log.info("管理员{} 修改商品:{}", loginUser.getUserId(), requestDTO);
        SjdFarmGoodsDO farmGoodsDO = SjdFarmGoodsDO.builder()
                .goodsId(requestDTO.getGoodsId())
                .goodsName(requestDTO.getGoodsName())
                .bigPicture(requestDTO.getBigPicture())
                .goodsTips(requestDTO.getGoodsTips())
                .goodsPrice(requestDTO.getGoodsPrice())
                .goodsDetail(requestDTO.getGoodsDetail())
                .goodsLevel(requestDTO.getGoodsLevel())
                .goodsTypeClass(requestDTO.getGoodsTypeClass())
                .goodsStorage(requestDTO.getGoodsStorage())
                .isOnline(requestDTO.getIsOnline())
                .build();
        List<String> goodsPicture = requestDTO.getGoodsPicture();
        String pictureJson = JSON.toJSONString(goodsPicture);
        farmGoodsDO.setGoodsPicture(pictureJson);
        farmGoodsMapper.updateByPrimaryKeySelective(farmGoodsDO);
        return AjaxResult.success();
    }

    /**
     * 农场商品上下线 管理平台
     *
     * @param requestDTO requestDTO
     * @param loginUser  loginUser
     * @return return
     */
    @Override
    public AjaxResult onlineOfflineGoods(SjdWebSiteFarmGoodsOnlineRequestDTO requestDTO, LoginUser loginUser) {
        log.info("管理员{} {}商品:{}", loginUser.getUserId(), requestDTO.getIsOnline() ? "上线" : "下线", requestDTO);
        SjdFarmGoodsDO sjdFarmGoodsDO = SjdFarmGoodsDO.builder()
                .goodsId(requestDTO.getGoodsId())
                .isOnline(requestDTO.getIsOnline())
                .build();
        farmGoodsMapper.updateByPrimaryKeySelective(sjdFarmGoodsDO);
        return AjaxResult.success();
    }

    /**
     * 删除农场商品 管理平台
     *
     * @param farmGoodsId farmGoodsId
     * @param loginUser   loginUser
     * @return return
     */
    @Override
    public AjaxResult deleteFarmGoods(Long farmGoodsId, LoginUser loginUser) {
        log.info("管理员{} 删除商品:{}", loginUser.getUserId(), farmGoodsId);
        farmGoodsMapper.logicDelete(farmGoodsId);
        return AjaxResult.success();
    }

    /**
     * 查询农场商品 管理平台
     *
     * @param requestDTO requestDTO
     * @return return
     */
    @Override
    public List<SjdWebSiteFarmGoodsQueryResponseDTO> webSiteQueryFarmGoods(SjdWebSiteFarmGoodsQueryRequestDTO requestDTO) {
        List<SjdWebSiteFarmGoodsQueryResponseDTO> responseDTOList = farmGoodsMapper.webSiteQueryFarmGoods(requestDTO.getGoodsId(), requestDTO.getGoodsName(), requestDTO.getGoodsTypeClass(), requestDTO.getIsOnline(), requestDTO.getGoodsLevel());
        responseDTOList.stream().peek(responseDTO->{
            String goodsPictureStr = responseDTO.getGoodsPictureStr();
            JSONArray jsonArray = JSONArray.parseArray(goodsPictureStr);
            if (jsonArray!=null) {
                responseDTO.setGoodsPicture(jsonArray.toJavaList(String.class));
            }else{
                responseDTO.setGoodsPicture(new ArrayList<>());
            }
        }).collect(Collectors.toList());
        return responseDTOList;
    }

    /**
     * 查询农场商品 小程序
     *
     * @param requestDTO requestDTO
     * @return return
     */
    @Override
    public List<SjdAppFarmGoodsQueryResponseDTO> appQueryFarmGoods(SjdAppFarmGoodsQueryRequestDTO requestDTO) {
        Long sjdMemberId = ThirdSessionHolder.getSjdMemberId();
        int maxLandLevelByMemberId = farmLandClaimOrderService.getMaxLandLevelByMemberId(sjdMemberId);
        List<SjdAppFarmGoodsQueryResponseDTO> responseDTOList = farmGoodsMapper.appQueryFarmGoods(requestDTO.getGoodsId(), requestDTO.getGoodsTypeClass(), maxLandLevelByMemberId);
        responseDTOList.stream().peek(responseDTO->{
            String goodsPictureStr = responseDTO.getGoodsPictureStr();
            JSONArray jsonArray = JSONArray.parseArray(goodsPictureStr);
            if (jsonArray!=null) {
                responseDTO.setGoodsPicture(jsonArray.toJavaList(String.class));
            }else{
                responseDTO.setGoodsPicture(new ArrayList<>());
            }
        }).collect(Collectors.toList());
        return responseDTOList;
    }

    /**
     * 查询农场商品 小程序
     *
     * @param farmGoodsId farmGoodsId
     * @return return
     */
    @Override
    public AjaxResult appQueryFarmGoodsById(Long farmGoodsId) {
        List<SjdAppFarmGoodsQueryResponseDTO> responseDOList = farmGoodsMapper.appQueryFarmGoods(farmGoodsId,null,null);
        if (CollectionUtils.isEmpty(responseDOList)){
            return AjaxResult.error("商品被删除或已经被下架");
        }
        SjdAppFarmGoodsQueryResponseDTO responseDTO = responseDOList.get(0);
        String pictureJson = responseDTO.getGoodsPictureStr();
        List<String> pictureUrl = JSONArray.parseArray(pictureJson, String.class);
        responseDTO.setGoodsPicture(pictureUrl);
        return AjaxResult.success(responseDTO);
    }

    /**
     * 减少库存
     *
     * @param goodsId   goodId
     * @param changeNum changeNum
     * @return MutablePair<Boolean result, String msg>
     */
    @Override
    public MutablePair<Boolean, String> decreaseStorage(@NotNull Long goodsId, @NotNull BigDecimal changeNum) {
        BigDecimal realChangeNum = changeNum.negate();
        MutablePair<Boolean, String> mutablePair = changeStorage(goodsId, realChangeNum);
        if (!mutablePair.left) {
            log.warn("减库存异常-" + mutablePair.right);
        }
        return mutablePair;
    }

    /**
     * 增加库存
     *
     * @param goodsId   goodsId
     * @param changeNum changeNum
     * @return return
     */
    @Override
    public MutablePair<Boolean, String> increaseStorage(@NotNull Long goodsId, @NotNull BigDecimal changeNum) {
        BigDecimal realChangeNum = changeNum.negate();
        MutablePair<Boolean, String> mutablePair = changeStorage(goodsId, realChangeNum);
        if (!mutablePair.left) {
            log.warn("加库存异常-" + mutablePair.right);
        }
        return mutablePair;
    }

    /**
     * 修改库存和总数
     *
     * @param goodsId   goodsId
     * @param changeNum sChangeNum
     * @return return
     */
    private synchronized MutablePair<Boolean, String> changeStorage(Long goodsId, BigDecimal changeNum) {
        MutablePair<Boolean, String> mutablePair = new MutablePair<>(false, "修改库存异常:");

        // 小于0 即 减库存
        if (BigDecimal.ZERO.compareTo(changeNum) > 0) {
            SjdFarmGoodsDO sjdFarmGoodsDO = farmGoodsMapper.selectByPrimaryKey(goodsId);
            if (sjdFarmGoodsDO == null) {
                mutablePair.right += ("商品" + goodsId + "不存在");
                return mutablePair;
            }
            //库存小于购买量 防止超卖
            if (sjdFarmGoodsDO.getGoodsStorage().compareTo(changeNum) < 0) {
                mutablePair.right += ("商品库存不足,减库存数:" + changeNum + ",库存当前剩余:" + sjdFarmGoodsDO.getGoodsStorage());
                return mutablePair;
            }
        }
        //变量不小于0,通用操作
        //开始操作数据库
        int i = farmGoodsMapper.updateStorage(goodsId, changeNum);
        if (i > 0) {
            return new MutablePair<>(Boolean.TRUE, "");
        }
        return mutablePair;
    }
}
